package com.tenglong.teacher.ui.dialog;


import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.HomeworkErrerTypeInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.HomeworkErrerDialogAdapter;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeworkErrorsFragment extends BaseFromBottomToShowDialogFragment implements HomeworkErrerDialogAdapter.HomeworkErrerDialogListener, View.OnClickListener {


    public static final String KEY_STR_TAGS = HomeworkErrorsFragment.class.getSimpleName() + "key_str_tags";
    public static final String KEY_SESSION_ID = HomeworkErrorsFragment.class.getSimpleName() + "key_sessionId";
    public static final String KEY_STUDENT_USER_ID = HomeworkErrorsFragment.class.getSimpleName() + "key_studentUserId";
    private RecyclerView mRecyclerView;
    private List<HomeworkErrerTypeInfo> infos;
    private HomeworkErrerDialogAdapter mAdapter;
    private View gx_tip;
    private int mLastPosition = -1;
    private ViewGroup tagsViewGroup;
    private String sessionId;
    private String studentUserId;
    private HomeworkErrorsDialogListener listener;
    private EditText qita;
    private List<String> selecteTags;

    public HomeworkErrorsFragment() {
        // Required empty public constructor
    }

    public static HomeworkErrorsFragment getInstance(ArrayList<String> strTags, String studentUserId, String sessionId) {
        HomeworkErrorsFragment f = new HomeworkErrorsFragment();
        Bundle params = new Bundle();
        params.putString(KEY_SESSION_ID, sessionId);
        params.putString(KEY_STUDENT_USER_ID, studentUserId);
        params.putStringArrayList(KEY_STR_TAGS, strTags);
        f.setArguments(params);
        return f;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Bundle params = getArguments();
        if (params == null) {
            dismiss();
            return;
        }
        if (!params.containsKey(KEY_STR_TAGS)) {
            dismiss();
            return;
        }
        List<String> checkTags = params.getStringArrayList(KEY_STR_TAGS);
        if (checkTags == null) {
            checkTags = new ArrayList<>();
        }
        infos = new ArrayList<>();
        for (String tag : checkTags) {
            HomeworkErrerTypeInfo info = new HomeworkErrerTypeInfo();
            info.isSelected = false;
            info.wordName = tag;
            infos.add(info);
        }

        if (params.containsKey(KEY_STUDENT_USER_ID)) {
            studentUserId = params.getString(KEY_STUDENT_USER_ID);
        } else {
            dismiss();
            return;
        }
        if (TextUtils.isEmpty(studentUserId)) {
            dismiss();
            return;
        }
        if (params.containsKey(KEY_SESSION_ID)) {
            sessionId = params.getString(KEY_SESSION_ID);
        } else {
            dismiss();
            return;
        }
        if (TextUtils.isEmpty(sessionId)) {
            dismiss();
            return;
        }
    }

    @Override
    protected View createView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_homework_errors, container, false);
    }

    @Override
    protected void viewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initView(view);
        initRecy();
        setAdapter();
        setListeners(view);
    }

    private void setListeners(View view) {
        mAdapter.setHomeworkErrerDialogListener(this);
        for (int i = 0; i < tagsViewGroup.getChildCount(); i++) {
            View childView = tagsViewGroup.getChildAt(i);
            childView.setTag("tag");
            childView.setOnClickListener(this);
        }
        view.findViewById(R.id.cancle).setOnClickListener(this);
        view.findViewById(R.id.affirm).setOnClickListener(this);
        mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ViewGroup.LayoutParams layoutParams = mRecyclerView.getLayoutParams();
                if (Build.VERSION.SDK_INT >= 16) {
                    mRecyclerView.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    mRecyclerView.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                int height = DensityUtil.dp2px((float) 95.4);
                if (mRecyclerView.getHeight() > height) {
                    layoutParams.height = height;
                }
                mRecyclerView.setLayoutParams(layoutParams);
            }
        });
    }

    private void setAdapter() {
        mAdapter = new HomeworkErrerDialogAdapter(infos);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initRecy() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    private void initView(View view) {
        tagsViewGroup = view.findViewById(R.id.tagsViewGroup);
        gx_tip = view.findViewById(R.id.gx_tip);
        mRecyclerView = view.findViewById(R.id.recyclerView);
        qita = view.findViewById(R.id.qita);
        if (infos == null){
            gx_tip.setVisibility(View.GONE);
        } else {
            gx_tip.setVisibility(infos.size() == 0 ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void onHomeworkErrerDialogClick(int position) {
        for (HomeworkErrerTypeInfo info : infos) {
            if (infos.indexOf(info) == position) {
                info.isSelected = true;
            } else {
                info.isSelected = false;
            }
        }
        mAdapter.notifyItemChanged(position);
        if (mLastPosition != -1) {
            mAdapter.notifyItemChanged(mLastPosition);
        }
        mLastPosition = position;
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();
        if (tag != null && tag.equals("tag")) {
            String text = ((TextView) v).getText().toString().trim();
            if (selecteTags == null) {
                selecteTags = new ArrayList<>();
            }
            if (v.isSelected()) {
                selecteTags.remove(text);
            } else {
                selecteTags.add(text);
            }
            v.setSelected(!v.isSelected());
        }
        switch (v.getId()) {
            case R.id.cancle:
                if (listener != null) {
                    listener.onDialogCancle();
                }
                dismiss();
                break;
            case R.id.affirm:
                if (listener != null) {
                    if (!TextUtils.isEmpty(qita.getText().toString().trim()) || (selecteTags != null && selecteTags.size() > 0)) {
                        if (!TextUtils.isEmpty(qita.getText().toString().trim())) {
                            if (selecteTags == null) {
                                selecteTags = new ArrayList<>();
                            }
                            selecteTags.add(qita.getText().toString().trim());
                        }
                        listener.onDialogAffirm(selecteTags);
                    } else {
                        ToastUtils.showCenterToast("必须选则错误标题");
                        return;
                    }
                }
                if (infos.size() == 0 || mLastPosition == -1) {
                    dismiss();
                    return;
                }
                boundWrongQuestionsBySessionIdAndWordName();
                break;
        }
    }

    private void boundWrongQuestionsBySessionIdAndWordName() {
        CreateRequestEntity.getWebService().boundWrongQuestionsBySessionIdAndWordName(sessionId,
                infos.get(mLastPosition).wordName, studentUserId).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    ToastUtils.showCenterToast(response.body().data ? "绑定成功" : "绑定失败");
                    if (response.body().data) {
                        dismiss();
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }

    public void setHomeworkErrorsDialogListener(HomeworkErrorsDialogListener listener) {
        this.listener = listener;
    }

    public interface HomeworkErrorsDialogListener {
        void onDialogCancle();

        void onDialogAffirm(List<String> selectTags);
    }
}
